package com.crm.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Time;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.crm.model.pojo.Complaint;
import com.crm.model.pojo.Customer;
import com.crm.model.pojo.Dictionary;
import com.crm.model.pojo.Qatable;
import com.crm.services.QAServices;
import com.crm.util.LoginUtil;
import com.github.pagehelper.PageInfo;
import com.mysql.jdbc.log.LogUtils;

import net.sf.jsqlparser.statement.update.Update;

/**
 * qa
 * @author 梁箐
 *
 */
@Controller
@RequestMapping("/aftersale")
public class QAController {
	
	@Autowired
	QAServices qaServices;
	
	/**
	 * 分页查询QA
	 * 
	 * @return
	 */
	@GetMapping("/qa")
	public ModelAndView findqa(Integer pageNum, Integer pageSize,Integer statueID,String search) {
		if (pageNum == null)
			pageNum = 1;
		if (pageSize == null)
			pageSize = 6;
		ModelAndView mv = new ModelAndView("aftersale/qa");
		System.out.println("QA！");
		// 查询qa
		List<Map<String, String>> selectPage = qaServices.selectPage(pageNum, pageSize, statueID, search);
		System.out.println(selectPage);
		String jsonString = JSONObject.toJSONString(selectPage);
		// 获取分页信息
		PageInfo<Map<String, String>> page = new PageInfo<Map<String, String>>(selectPage);
		System.out.println(page);
		String pageInfo = JSONObject.toJSONString(page);
		System.out.println(page);
		mv.addObject("list", jsonString);
		mv.addObject("page", page);
		mv.addObject("pageinfo", pageInfo);
		return mv;
	}

	/**
	 * 分页查询获取qa（刷新表单）
	 * @param pageNum
	 * @param pageSize
	 * @param statueID
	 * @param search
	 * @return
	 */
	@PostMapping("/qa")
	@ResponseBody	
	public PageInfo<Map<String, String>> findqaNew(Integer pageNum, Integer pageSize,Integer statueID,String search) {
		if (pageNum == null)
			pageNum = 1;
		if (pageSize == null)
			pageSize = 6;
		//分页查询qa
		System.out.println("QATable:"+pageNum+"\t"+pageSize+"\t"+statueID+"\t"+search);
		List<Map<String, String>> selectPage = qaServices.selectPage(pageNum, pageSize, statueID, search);
		//获取分页信息
		PageInfo<Map<String, String>> page = new PageInfo<Map<String, String>>(selectPage);
		return page;
	}

	/**
	 * id逻辑删除
	 * 
	 * @param qaid
	 * @return
	 */
	@RequestMapping("/deleteoneQA")
	@ResponseBody
	public int deleteone(@RequestParam("ID") Integer qaid) {
		System.out.println("删除单个:" + qaid);
		qaServices.deleteByStatue(qaid);
		return 1;
	}
	
	/**
	 * 查询单个投诉
	 * @param qaid
	 * @return
	 */
	@PostMapping("/QAOne")
	@ResponseBody
	public JSONObject getQAByqaid(@RequestParam("qa_id") Integer qaid) {
		//根据编号查询增加点击次数
		int updateNum = qaServices.updateNum(qaid);
		//根据qa编号查询单条qa信息
		Map<String, String> selectOneQA = qaServices.selectOneByid(qaid);
		System.out.println("编号为："+qaid+"的QA信息："+selectOneQA);
		//查询qa分类
		List<Map<String, String>> selectQAclassity = qaServices.selectQAtype(1386);
		System.out.println("QA分类：" + selectQAclassity);
		//查询qa状态
		List<Map<String, String>> selectQAtype = qaServices.selectQAtype(1391);
		System.out.println("QA状态：" + selectQAtype);
		//查询qa作者
		List<Map<String, String>> selectQAauthor = qaServices.selectAllAuthor();
		System.out.println("QA作者：" + selectQAauthor);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("oneQAclassity", selectQAclassity);
		jsonObject.put("oneQAInfo", selectOneQA);
		jsonObject.put("oneQAauthor", selectQAauthor);
		jsonObject.put("oneQAtype", selectQAtype);
		return jsonObject;
	}
	
	
	/**
	 * 编辑QA
	 */
	@PostMapping("/updateQA")
	@ResponseBody
	public String updateQA(@RequestParam("ID") Integer qaid,
			@RequestParam(name = "qaquestion", required = false) String question,
			@RequestParam(name = "qaanswer", required = false) String answer,
			@RequestParam(name = "qaclassity", required = false) Integer classifyID,
			@RequestParam(name = "qastatue", required = false) Integer status,
			@RequestParam(name = "qadate", required = false) String date,
			@RequestParam(name = "comreturn", required = false) String num,
			@RequestParam(name = "qaauthor", required = false) Integer author) {
		// 转换日期格式
		java.sql.Date datenew = java.sql.Date.valueOf(date.substring(0, 10));
		System.out.println("时间日期："+datenew);
		Qatable qatable = new Qatable();
		//转换点击次数
		System.out.println("qa编号："+qaid);
		//根据编号查询增加点击次数
		Map<String, String> selectNum = qaServices.selectNum(qaid);
		Object object = selectNum.get("num");
		Integer valueOf = Integer.valueOf(object.toString());
		BigDecimal newnum = new BigDecimal(valueOf);
		System.out.println("修改后点击次数："+newnum);
		// 修改
		qatable.setQaId(qaid);//qa编号
		qatable.setQaQuestion(question);//问题
		qatable.setQaAnswer(answer);//回答
		qatable.setQa_classifyID(classifyID);//qa分类
		qatable.setQaStatus(status);//qa状态
		qatable.setQaDate(datenew);//qa创建日期
		qatable.setQaNum(newnum);//qa点击次数
		qatable.setQaauthor(author);//qa创建者
		qatable.setDeletestatue(1206);// 删除状态
		qaServices.addQA(qatable);
		System.out.println("更新：" + qatable);
		return "编辑！";
	}
	
	/**
	 * 新增时查询对应可选数据
	 * @return
	 */
	@PostMapping("/chooseQAOptions")
	@ResponseBody
	public JSONObject addoptions() {
		//查询qa分类
		List<Map<String, String>> selectQAclassity = qaServices.selectQAtype(1386);
		System.out.println("QA分类：" + selectQAclassity);
		/*//查询qa状态
		List<Map<String, String>> selectQAtype = qaServices.selectQAtype(1391);
		System.out.println("QA状态：" + selectQAtype);*/
		//查询qa作者
		List<Map<String, String>> selectQAauthor = qaServices.selectAllAuthor();
		System.out.println("QA作者：" + selectQAauthor);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("oneQAclassity", selectQAclassity);
		jsonObject.put("oneQAauthor", selectQAauthor);
		jsonObject.put("user", LoginUtil.getUser());
		//jsonObject.put("oneQAtype", selectQAtype);
		return jsonObject;
	}
	
	/**
	 * 新增QA
	 */
	@PostMapping("/addQA")
	@ResponseBody
	public String addQA(@RequestParam(name = "qaquestion", required = false) String question,
			@RequestParam(name = "qaanswer", required = false) String answer,
			@RequestParam(name = "qaclassity", required = false) Integer classifyID,
			@RequestParam(name = "qadate", required = false) String date,
			@RequestParam(name = "comreturn", required = false) String num,
			@RequestParam(name = "qaauthor", required = false) Integer author) {
		// 转换日期格式
		java.sql.Date datenew = java.sql.Date.valueOf(date.substring(0, 10));
		System.out.println("时间日期："+datenew);
		Qatable qatable = new Qatable();
		// 新增
		qatable.setQaQuestion(question);//问题
		qatable.setQaAnswer(answer);//回答
		qatable.setQa_classifyID(classifyID);//qa分类
		qatable.setQaStatus(1392);//qa状态(正常)
		qatable.setQaDate(datenew);//qa创建日期
		qatable.setQaNum(new BigDecimal("0"));//qa点击次数0
		qatable.setQaauthor(author);//qa创建者
		qatable.setDeletestatue(1206);// 删除状态
		qaServices.addQA(qatable);
		System.out.println("新增：" + qatable);
		return "新增！";
	}
	
	
	/**
	 * 导出
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "QAExcelDownloads", method = RequestMethod.GET)
    public void downloadAllClassmate(HttpServletResponse response) throws IOException {
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("QA！");

        List<Map<String, String>> selectAll = qaServices.selectAllInfo();
      
        String fileName = "qainfo"  + ".xls";//设置要导出的文件的名字
        //新增数据行，并且设置单元格数据

        int rowNum = 1;

        String[] headers = { "编号", "问题","回答","分类", "次数","状态"};
        //headers表示excel表中第一行的表头

        HSSFRow row = sheet.createRow(0);
        //在excel表中添加表头

        for(int i=0;i<headers.length;i++){
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }

        //在表中存放查询到的数据放入对应的列
        for (Map<String, String> map : selectAll) {
        	HSSFRow row1 = sheet.createRow(rowNum);
            row1.createCell(0).setCellValue(String.valueOf(map.get("ID")));
            row1.createCell(1).setCellValue(String.valueOf(map.get("question")));
            row1.createCell(2).setCellValue(String.valueOf(map.get("answer")));
            row1.createCell(3).setCellValue(map.get("qaclassify"));
            row1.createCell(4).setCellValue(String.valueOf(map.get("num")));
            row1.createCell(5).setCellValue(map.get("qastatus"));
            rowNum++;
      		}
              
        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.flushBuffer();
        workbook.write(response.getOutputStream());
    }

	
}
